import {Component, OnDestroy, OnInit} from '@angular/core';
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {UserInfoService} from "../service/user-info.service";
import {NzMessageService} from "ng-zorro-antd/message";
import {HttpUtilService} from "../../../../../services/http/http-util.service";
import {ActivatedRoute} from "@angular/router";
import {NzModalService} from "ng-zorro-antd/modal";
import {RoleSelectionComponent} from "../../role/role-selection/role-selection.component";
import {forkJoin, Subscription} from "rxjs";
import {UserRoleService} from "../../services/user-role.service";
import {RoleInfoService} from "../../role/service/role-info.service";
import {BarnRole} from "../../role/entity/barn-role";
import {tap} from "rxjs/operators";

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styleUrls: ['./user-edit.component.less']
})
export class UserEditComponent implements OnInit, OnDestroy {

  validateForm = new FormGroup({
    userName: new FormControl(null, [Validators.required, Validators.maxLength(20)]),
    pid: new FormControl(null),
    userAccount: new FormControl(null, [Validators.required, Validators.maxLength(20)]),
    enable: new FormControl("1", [Validators.required, Validators.maxLength(20)])
  })

  loading = false
  isVisible = false

  roles: BarnRole[] = []
  teamRoles: BarnRole[] = []

  modalHook$: Subscription

  constructor(private userInfoService: UserInfoService, private msg: NzMessageService, private httpUtilService: HttpUtilService,
              private routeInfo: ActivatedRoute, private modal: NzModalService, private roleUserService: UserRoleService,
              private roleService: RoleInfoService) {
  }

  ngOnInit(): void {
    const pid = this.routeInfo.snapshot.queryParams["pid"];
    if (pid) {
      this.loading = true
      // this.userInfoService.getById(pid).subscribe(value => {
      //   if (value) {
      //     this.validateForm.patchValue(value);
      //   }
      // }, () => this.loading = false, () => this.getRoles(pid))


      this.userInfoService.getById(pid).pipe(
        tap(value => {
          if (value) {
            this.validateForm.patchValue(value);
            return this.getRoles(pid)
          }
        })
      ).subscribe()
    }
  }

  submitForm() {

    if (this.validateForm.valid) {
      const user = this.validateForm.getRawValue();
      this.loading = true
      this.userInfoService.save(user).subscribe(value => {
        this.validateForm.patchValue(value)
        this.loading = false
        this.msg.success("保存成功")
      }, error => {
        this.loading = false
        if (error.error.status === "ACCOUNT_EXISTS") {
          this.msg.error("账号已存在，请更换。")
        } else {
          this.httpUtilService.errorDialog(error.url, error.static, error.message,
            error.error?.status, error.error?.message + "\n" + error.error?.exception)
        }
      });
    } else {
      for (const i in this.validateForm.controls) {
        this.validateForm.controls[i].markAsDirty();
        this.validateForm.controls[i].updateValueAndValidity();
      }
    }

  }

  get pid() {
    return this.validateForm.get("pid").value
  }

  addRoleDialog() {

    const modalHook = this.modal.create({
      nzTitle: '添加角色',
      nzContent: RoleSelectionComponent,
      nzFooter: null,
      nzWidth: 1000,
      nzComponentParams: {
        height: 600, multi: true
      }
    })
    if (this.modalHook$) {
      this.modalHook$.unsubscribe()
    }
    this.modalHook$ = modalHook.afterClose.asObservable().subscribe(value => {
      if (value && value.length) {
        this.addRoles(value);
      }
    });
  }

  addRoles(roleIds: string[]) {
    if (!roleIds) {
      return
    }
    const pid = this.validateForm.get("pid").value;
    this.loading = true
    this.roleUserService.addRoleIds(pid, roleIds)
      .subscribe(value => {
        this.msg.success("添加成功");
        this.loading = false
        this.getRoles(pid)
      }, () => this.loading = false)

  }

  getRoles(pid) {
    this.loading = true
    const r1$ = this.roleService.getByUserId(pid).pipe(
      tap(value => {
        this.roles = value || []
      })
    );
    const r2$ = this.roleService.getByUserTeam(pid).pipe(
      tap(value => {
        this.teamRoles = value || []
      })
    )

    const f$ = forkJoin([r1$, r2$]);
    const s$ = f$.subscribe(() => {
      this.loading = false
    }, () => {
      this.loading = false;
      s$.unsubscribe()
    }, () => s$.unsubscribe())
    return f$
  }

  deleteRole(roleId) {
    const pid = this.validateForm.get("pid").value;
    this.loading = true
    this.roleUserService.delete(roleId, pid)
      .subscribe(value => {
        this.getRoles(pid)
        this.loading = false
      }, () => this.loading = false)
  }

  ngOnDestroy(): void {
    if (this.modalHook$) {
      this.modalHook$.unsubscribe()
    }
  }

}
